import 'package:rjpb/shared/utils/storage_util.dart';
import 'package:rjpb/shared/constants/account_constant.dart';
import 'package:rjpb/page/login/apis/login_api.dart';

class AuthService {
  static Future<bool> login(String username, String password) async {
    final response = await LoginApi.login(username, password);
    print("登录信息 ${response}");
    if (response != null && response['code'] == 200) {
      final token = response["data"]?["access_token"];
      final userId = response["data"]?["userId"];
      final expiryTime = response["data"]?["expires_in"];
      if (token != null) {
        await StorageUtil.setToken(token.toString());
        await StorageUtil.setItem(AccountConstant.userId, userId);
        await StorageUtil.setItem('expiryTime',
            DateTime.now().millisecondsSinceEpoch + expiryTime * 1000);
        return true;
      }
    }
    return false;
  }

  static Future<void> saveToken(String accessToken, int expiryTime) async {
    await StorageUtil.setToken(accessToken);
    await StorageUtil.setItem('expiryTime', expiryTime);
  }

  static Future<bool> isTokenValid() async {
    final token = await StorageUtil.getToken(); // 异步获取 token
    final expiryTime =
        await StorageUtil.getItem('expiryTime') as int?; // 异步获取过期时间
    if (token.isEmpty || expiryTime == null) {
      return false;
    }
    return DateTime.now().millisecondsSinceEpoch < expiryTime;
  }

  static Future<bool> isTokenExpired() async {
    // final expiryTime = await getTokenExpiry();
    final expiryTime = await StorageUtil.getItem('expiryTime') as int?;
    if (expiryTime == null) return true; // 如果没有过期时间，认为 token 已过期
    // return DateTime.now().millisecondsSinceEpoch > expiryTime;
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    print('当前时间: $currentTime');
    print('过期时间: $expiryTime');

    return currentTime > expiryTime;
  }
}
